﻿

using DualPlaneFR4Paster.Models;
using netDxf.Entities;
using netDxf.Header;
using netDxf;
using Prism.Commands;
using Prism.Ioc;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows.Forms;
using System.Linq;
using Prism.Services.Dialogs;
using System.Diagnostics;
using System.Windows.Controls;
using System;
using System.Windows.Media.Media3D;
using DualPlaneFR4Paster.Extensions;
using netDxf.Tables;

namespace DualPlaneFR4Paster.ViewModels.Dialogs
{
    public class PastePointDialogViewModel : DialogViewModel
    {
        #region 变量
        double OrgWidth = 0;
        double OrgHeight = 0;
        double OrgPX = 0, OrgPY = 0, OrgNX = 0, OrgNY = 0;
        string lostfocusColor = "";
        double lostBorderThickness = 1;
        string partNum = string.Empty;
        #endregion
        #region 属性
        private ObservableCollection<LwPolylineDisp> lwPolylineList;
        public ObservableCollection<LwPolylineDisp> LwPolylineList
        {
            get { return lwPolylineList; }
            set { SetProperty(ref lwPolylineList, value); }
        }

        private int floorIndex;
        public int FloorIndex
        {
            get { return floorIndex; }
            set { SetProperty(ref floorIndex, value); }
        }
        private ObservableCollection<ProductDisp> productList1;
        public ObservableCollection<ProductDisp> ProductList1
        {
            get { return productList1; }
            set { SetProperty(ref productList1, value); }
        }
        private ProductEditDisp productEdit;
        public ProductEditDisp ProductEdit
        {
            get { return productEdit; }
            set { SetProperty(ref productEdit, value); }
        }
        private ObservableCollection<PcsDisp> pcsList1;
        public ObservableCollection<PcsDisp> PcsList1
        {
            get { return pcsList1; }
            set { SetProperty(ref pcsList1, value); }
        }
        private PcsEditDisp pcsEdit;    
        public PcsEditDisp PcsEdit
        {
            get { return pcsEdit; }
            set { SetProperty(ref pcsEdit, value); }
        }
        private PcsEditDeltaDisp pcsDeltaEdit;
        public PcsEditDeltaDisp PcsDeltaEdit
        {
            get { return pcsDeltaEdit; }
            set { SetProperty(ref pcsDeltaEdit, value); }
        }
        private bool isAssistantPointEditVisible;
        public bool IsAssistantPointEditVisible
        {
            get { return isAssistantPointEditVisible; }
            set { SetProperty(ref isAssistantPointEditVisible, value); }
        }
        private ObservableCollection<AxisPointDisp> pointList1;
        public ObservableCollection<AxisPointDisp> PointList1
        {
            get { return pointList1; }
            set { SetProperty(ref pointList1, value); }
        }
        private int suckerEditDeltaIndex;
        public int SuckerEditDeltaIndex
        {
            get { return suckerEditDeltaIndex; }
            set { SetProperty(ref suckerEditDeltaIndex, value); }
        }
        #endregion
        #region 命令
        private DelegateCommand openFileCommand;
        public DelegateCommand OpenFileCommand =>
            openFileCommand ?? (openFileCommand = new DelegateCommand(ExecuteOpenFileCommand));

        private DelegateCommand<object> selectFloorCommand;
        public DelegateCommand<object> SelectFloorCommand =>
            selectFloorCommand ?? (selectFloorCommand = new DelegateCommand<object>(ExecuteSelectFloorCommand));
        private DelegateCommand<ProductDisp> productList1SelectCommand;
        public DelegateCommand<ProductDisp> ProductList1SelectCommand =>
            productList1SelectCommand ?? (productList1SelectCommand = new DelegateCommand<ProductDisp>(ExecuteProductList1SelectCommand));
        private DelegateCommand<ProductDisp> productList1LostKeyboardFocusCommand;
        public DelegateCommand<ProductDisp> ProductList1LostKeyboardFocusCommand =>
            productList1LostKeyboardFocusCommand ?? (productList1LostKeyboardFocusCommand = new DelegateCommand<ProductDisp>(ExecuteProductList1LostKeyboardFocusCommand));
        private DelegateCommand<ProductDisp> editUpdateProductCommand;
        public DelegateCommand<ProductDisp> EditUpdateProductCommand =>
            editUpdateProductCommand ?? (editUpdateProductCommand = new DelegateCommand<ProductDisp>(ExecuteEditUpdateProductCommand));
        private DelegateCommand<ProductDisp> productListUpShiftCommand;
        public DelegateCommand<ProductDisp> ProductListUpShiftCommand =>
            productListUpShiftCommand ?? (productListUpShiftCommand = new DelegateCommand<ProductDisp>(ExecuteProductListUpShiftCommand));
        private DelegateCommand<ProductDisp> productListDownShiftCommand;
        public DelegateCommand<ProductDisp> ProductListDownShiftCommand =>
            productListDownShiftCommand ?? (productListDownShiftCommand = new DelegateCommand<ProductDisp>(ExecuteProductListDownShiftCommand));
        private DelegateCommand<PcsDisp> pcsList1SelectCommand;
        public DelegateCommand<PcsDisp> PcsList1SelectCommand =>
            pcsList1SelectCommand ?? (pcsList1SelectCommand = new DelegateCommand<PcsDisp>(ExecutePcsList1SelectCommand));
        private DelegateCommand<PcsDisp> pcsList1LostKeyboardFocusCommand;
        public DelegateCommand<PcsDisp> PcsList1LostKeyboardFocusCommand =>
            pcsList1LostKeyboardFocusCommand ?? (pcsList1LostKeyboardFocusCommand = new DelegateCommand<PcsDisp>(ExecutePcsList1LostKeyboardFocusCommand));
        private DelegateCommand<PcsDisp> editUpdatePcsCommand;
        public DelegateCommand<PcsDisp> EditUpdatePcsCommand =>
            editUpdatePcsCommand ?? (editUpdatePcsCommand = new DelegateCommand<PcsDisp>(ExecuteEditUpdatePcsCommand));
        private DelegateCommand<ProductDisp> productList1IsUseCheckCommand;
        public DelegateCommand<ProductDisp> ProductList1IsUseCheckCommand =>
            productList1IsUseCheckCommand ?? (productList1IsUseCheckCommand = new DelegateCommand<ProductDisp>(ExecuteProductList1IsUseCheckCommand));
        private DelegateCommand<PcsDisp> pcsList1IsUseCheckCommand;
        public DelegateCommand<PcsDisp> PcsList1IsUseCheckCommand =>
            pcsList1IsUseCheckCommand ?? (pcsList1IsUseCheckCommand = new DelegateCommand<PcsDisp>(ExecutePcsList1IsUseCheckCommand));
        private DelegateCommand<object> selectSuckerEditDeltaCommand;
        public DelegateCommand<object> SelectSuckerEditDeltaCommand =>
            selectSuckerEditDeltaCommand ?? (selectSuckerEditDeltaCommand = new DelegateCommand<object>(ExecuteSelectSuckerEditDeltaCommand));
        private DelegateCommand batchEditPointCommand;
        public DelegateCommand BatchEditPointCommand =>
            batchEditPointCommand ?? (batchEditPointCommand = new DelegateCommand(ExecuteBatchEditPointCommand));

        void ExecuteBatchEditPointCommand()
        {
            string floorName = FloorIndex == 1 ? "上层" : "下层";
            if (_dialogHostService.MessageBox(MessageType.Confirm, "确认", $"确定批量更新\"{floorName}\"-\"吸嘴{SuckerEditDeltaIndex + 1}\"的点位吗？") == ButtonResult.Yes)
            {
                int changeCount = 0;
                using (var db = new DTContext(partNum))
                {
                    var _products = db.MProducts.Where(p => p.Floor == FloorIndex && p.IsUse);
                    if (_products.Any())
                    {
                        foreach (var _product in _products.ToList())
                        {
                            var _pcses = _product.Pcses.Where(pcs => pcs.IsUse && pcs.PickIndex == SuckerEditDeltaIndex);
                            if (_pcses.Any())
                            {
                                foreach (var _pcs in _pcses.ToList())
                                {
                                    _pcs.X += PcsDeltaEdit.X;
                                    _pcs.Y += PcsDeltaEdit.Y;
                                    _pcs.Z += PcsDeltaEdit.Z;
                                    _pcs.R += PcsDeltaEdit.R;
                                    if (FloorIndex == 2)
                                    {
                                        _pcs.X1 += PcsDeltaEdit.X1;
                                        _pcs.Y1 += PcsDeltaEdit.Y1;
                                        _pcs.Z1 += PcsDeltaEdit.Z1;
                                        _pcs.R1 += PcsDeltaEdit.R1;
                                    }
                                    changeCount++;
                                }
                            }
                        }
                        if (changeCount > 0)
                        {
                            db.SaveChanges();
                            PcsList1.Clear();
                            PcsEdit = null;              
                        }
                        _dialogHostService.MessageBox(MessageType.Message, "信息", $"更新{changeCount}个贴合位。");
                        PcsDeltaEdit.X = 0;
                        PcsDeltaEdit.Y = 0;
                        PcsDeltaEdit.Z = 0;
                        PcsDeltaEdit.R = 0;
                        PcsDeltaEdit.X1 = 0;
                        PcsDeltaEdit.Y1 = 0;
                        PcsDeltaEdit.Z1 = 0;
                        PcsDeltaEdit.R1 = 0;
                    }
                    else
                    {
                        _dialogHostService.MessageBox(MessageType.Message,"信息","未选择任何产品");
                    }
                }
            }
        }
        void ExecuteSelectSuckerEditDeltaCommand(object obj)
        {
            SuckerEditDeltaIndex = int.Parse(obj.ToString());
        }
        void ExecutePcsList1IsUseCheckCommand(PcsDisp pcs)
        {
            if (pcs != null)
            {
                using (var db = new DTContext(partNum))
                {
                    var _product = db.MProducts.FirstOrDefault(p => p.Floor == FloorIndex && p.PcsOrder == pcs.ProductId);
                    if (_product != null)
                    {
                        if (_product.Pcses != null)
                        {
                            var _pcs = _product.Pcses.FirstOrDefault(p => p.Index == pcs.Id);
                            if (_pcs != null)
                            {
                                _pcs.IsUse = pcs.IsUse;
                                db.SaveChanges();
                            }
                        }
                    }
                }
            }
        }
        void ExecuteProductList1IsUseCheckCommand(ProductDisp product)
        {
            if (product != null)
            {
                using (var db = new DTContext(partNum))
                {
                    var _product = db.MProducts.FirstOrDefault(p => p.Floor == FloorIndex && p.PcsOrder == product.Id);
                    if (_product != null)
                    {
                        _product.IsUse = product.IsUse;
                        db.SaveChanges();
                    }
                }
            }
        }
        void ExecuteEditUpdatePcsCommand(PcsDisp pcs)
        {
            if (pcs != null)
            {
                pcs.X = PcsEdit.X;
                pcs.Y = PcsEdit.Y;
                pcs.R = PcsEdit.R;
                pcs.Z = PcsEdit.Z;
                pcs.X1 = PcsEdit.X1;
                pcs.Y1 = PcsEdit.Y1;
                pcs.R1 = PcsEdit.R1;
                pcs.Z1 = PcsEdit.Z1;
                pcs.PickIndex = PcsEdit.PickIndex;
                pcs.PressIndex = PcsEdit.PressIndex;
                double width = 0, height = 0;
                using (var db = new DTContext(partNum))
                {
                    var _product = db.MProducts.FirstOrDefault(p => p.PcsOrder == pcs.ProductId && p.Floor == FloorIndex);
                    if (_product != null)
                    {
                        if (_product.Pcses != null)
                        {
                            var _pcs = _product.Pcses.FirstOrDefault(p => p.Index == pcs.Id);
                            if (_pcs != null)
                            {
                                width = _pcs.Width;
                                height = _pcs.Height;
                                _pcs.X = PcsEdit.X;
                                _pcs.Y = PcsEdit.Y;
                                _pcs.R = PcsEdit.R;
                                _pcs.Z = PcsEdit.Z;
                                _pcs.X1 = PcsEdit.X1;
                                _pcs.Y1 = PcsEdit.Y1;
                                _pcs.R1 = PcsEdit.R1;
                                _pcs.Z1 = PcsEdit.Z1;
                                _pcs.PickIndex = PcsEdit.PickIndex;
                                _pcs.PressIndex = PcsEdit.PressIndex;
                                db.SaveChanges();
                            }
                        }
                    }
                }
                var orgPoint = PointList1.FirstOrDefault(p => p.Name == "OrgBoard" && p.Floor == FloorIndex);
                if (width != 0 && height != 0)
                {
                    var lwPoly = LwPolylineList.FirstOrDefault(p => p.Id == pcs.Id && p.Floor == FloorIndex && p.Kind == 2 && p.ProductId == pcs.ProductId);
                    if (lwPoly != null)
                    {
                        switch (FloorIndex)
                        {
                            case 1:
                                lwPoly.Left = 10 + (pcs.X - width / 2 - (orgPoint.X - OrgPX)) / 2;
                                lwPoly.Bottom = 10 + (pcs.Y - height / 2 - (orgPoint.Y - OrgPY)) / 2;
                                break;
                            case 2:
                                lwPoly.Left = 10 + (OrgWidth - ((pcs.X - (orgPoint.X - OrgNX)) + width / 2)) / 2;
                                lwPoly.Bottom = 10 + (pcs.Y - height / 2 - (orgPoint.Y - OrgPY)) / 2;
                                break;
                            default:
                                break;
                        }
                 
                    }
                }
                _dialogHostService.MessageBox(MessageType.Message, "信息", "更新完成");
            }
            else
            {
                _dialogHostService.MessageBox(MessageType.Message, "信息", "未选择任何项目");
            }
        }
        void ExecutePcsList1LostKeyboardFocusCommand(PcsDisp pcs)
        {
            var lwPoly = LwPolylineList.FirstOrDefault(p => p.Id == pcs.Id && p.Floor == FloorIndex && p.Kind == 2 && p.ProductId == pcs.ProductId);
            if (lwPoly != null)
            {
                lwPoly.BorderColor = lostfocusColor;
                lwPoly.BorderThickness = lostBorderThickness;
            }
        }
        void ExecutePcsList1SelectCommand(PcsDisp pcs)
        {
            if (pcs != null)
            {
                PcsEdit = new PcsEditDisp { 
                    Id = pcs.Id,
                    ProductId = pcs.ProductId,
                    X = pcs.X,
                    Y = pcs.Y,
                    R = pcs.R,
                    Z = pcs.Z,
                    X1 = pcs.X1,
                    Y1 = pcs.Y1,
                    R1 = pcs.R1,
                    Z1 = pcs.Z1,
                    PickIndex = pcs.PickIndex,
                    PressIndex = pcs.PressIndex
                };
                var lwPoly = LwPolylineList.FirstOrDefault(p => p.Id == pcs.Id && p.Floor == FloorIndex && p.Kind == 2 && p.ProductId == pcs.ProductId);
                if (lwPoly != null)
                {
                    lostfocusColor = lwPoly.BorderColor;
                    lostBorderThickness = lwPoly.BorderThickness;
                    lwPoly.BorderColor = "#00FF00";
                    lwPoly.BorderThickness = 3;
                }
            }
        }
        void ExecuteProductListDownShiftCommand(ProductDisp product)
        {
            if (product != null)
            {
                bool changed = false;
                using (var db = new DTContext(partNum))
                {
                    var curp = db.MProducts.FirstOrDefault(p => p.Floor == FloorIndex && p.PcsOrder == product.Id);
                    if (curp != null)
                    {
                        var mp = db.MProducts.Where(p => p.Floor == FloorIndex && p.PcsOrder > product.Id).OrderBy(p => p.PcsOrder).FirstOrDefault();
                        if (mp != null)
                        {
                            int box = mp.PcsOrder;
                            int box1 = curp.PcsOrder;
                            mp.PcsOrder = box1;
                            curp.PcsOrder = box;
                            db.SaveChanges();
                            changed = true;
                        }
                    }
                }
                if (changed)
                {
                    LoadProductList(FloorIndex);
                    ReLoadProductLwPolylineList(FloorIndex);
                }
            }
            else
            {
                _dialogHostService.MessageBox(MessageType.Message, "信息", "未选择任何项目");
            }
        }
        void ExecuteProductListUpShiftCommand(ProductDisp product)
        {
            if (product != null)
            {
                bool changed = false;
                using (var db = new DTContext(partNum))
                {
                    var curp = db.MProducts.FirstOrDefault(p => p.Floor == FloorIndex && p.PcsOrder == product.Id);
                    if (curp != null)
                    {
                        var mp = db.MProducts.Where(p => p.Floor == FloorIndex && p.PcsOrder < product.Id).OrderByDescending(p => p.PcsOrder).FirstOrDefault();
                        if (mp != null)
                        {
                            int box = mp.PcsOrder;
                            int box1 = curp.PcsOrder;
                            mp.PcsOrder = box1;
                            curp.PcsOrder = box;
                            db.SaveChanges();
                            changed = true;
                        }
                    }
                }
                if (changed)
                {
                    LoadProductList(FloorIndex);
                    ReLoadProductLwPolylineList(FloorIndex);
                }
            }
            else
            {
                _dialogHostService.MessageBox(MessageType.Message, "信息", "未选择任何项目");
            }
        }
        void ExecuteEditUpdateProductCommand(ProductDisp product)
        {
            if (product != null)
            {
                product.Direction = ProductEdit.Direction == 0 ? "增" : "减";
                product.IsReverse = ProductEdit.IsReverse == 0 ? "否" : "是";
                product.StartX = ProductEdit.StartX;
                product.StartY = ProductEdit.StartY;
                product.EndX = ProductEdit.EndX;
                product.EndY = ProductEdit.EndY;
                var lwPoly = LwPolylineList.FirstOrDefault(p => p.Id == product.Id && p.Floor == FloorIndex && p.Kind == 1);
                var orgPoint = PointList1.FirstOrDefault(p => p.Name == "OrgBoard" && p.Floor == FloorIndex);
                if (lwPoly != null)
                {
                    switch (FloorIndex)
                    {
                        case 1:
                            lwPoly.Left = 10 + (ProductEdit.StartX - (orgPoint.X - OrgPX)) / 2;
                            lwPoly.Bottom = 10 + (ProductEdit.StartY - (orgPoint.Y - OrgPY)) / 2;
                            break;
                        case 2:
                            lwPoly.Left = 10 + (OrgWidth - (ProductEdit.StartX - (orgPoint.X - OrgNX)) - (ProductEdit.EndX - ProductEdit.StartX)) / 2;
                            lwPoly.Bottom = 10 + (ProductEdit.StartY - (orgPoint.Y - OrgNY)) / 2;
                            break;
                        default:
                            break;
                    }
                    lwPoly.Width = (ProductEdit.EndX - ProductEdit.StartX) / 2;
                    lwPoly.Height = (ProductEdit.EndY - ProductEdit.StartY) / 2;
                }
                using (var db = new DTContext(partNum))
                {
                    var _product = db.MProducts.FirstOrDefault(p => p.PcsOrder == product.Id && p.Floor == FloorIndex);
                    if (_product != null)
                    {
                        _product.Direction = ProductEdit.Direction;
                        _product.IsReverse = ProductEdit.IsReverse == 1;
                        _product.StartX = ProductEdit.StartX;
                        _product.StartY = ProductEdit.StartY;
                        _product.EndX = ProductEdit.EndX;
                        _product.EndY = ProductEdit.EndY;
                        db.SaveChanges();
                    }
                }
                _dialogHostService.MessageBox(MessageType.Message, "信息", "更新完成");
            }
            else
            {
                _dialogHostService.MessageBox(MessageType.Message, "信息", "未选择任何项目");
            }
        }
        void ExecuteProductList1LostKeyboardFocusCommand(ProductDisp product)
        {
            //Debug.WriteLine(product.Id);
            var lwPoly = LwPolylineList.FirstOrDefault(p => p.Id == product.Id && p.Floor == FloorIndex && p.Kind == 1);
            if (lwPoly != null)
            {
                lwPoly.BorderColor = lostfocusColor;
                lwPoly.BorderThickness = lostBorderThickness;
            }
        }
        void ExecuteProductList1SelectCommand(ProductDisp product)
        {
            if (product != null)
            {                
                ProductEdit = new ProductEditDisp()
                {
                    Id = product.Id,
                    Direction = product.Direction == "增" ? 0 : 1,
                    IsReverse = product.IsReverse == "否" ? 0 : 1,
                    StartX = product.StartX,
                    StartY = product.StartY,
                    EndX = product.EndX,
                    EndY = product.EndY
                };
                var lwPoly = LwPolylineList.FirstOrDefault(p => p.Id == product.Id && p.Floor == FloorIndex && p.Kind == 1);
                if (lwPoly != null)
                {
                    lostfocusColor = lwPoly.BorderColor;
                    lostBorderThickness = lwPoly.BorderThickness;
                    lwPoly.BorderColor = "#00FF00";
                    lwPoly.BorderThickness = 3;
                }
                using (var db = new DTContext(partNum))
                {
                    var product1 = db.MProducts.FirstOrDefault(p => p.Floor == FloorIndex && p.PcsOrder == product.Id);
                    if (product1 != null)
                    {
                        var pcses = product1.Pcses.OrderBy(pcs => pcs.Index).ToList();
                        if (pcses.Any())
                        {
                            PcsList1.Clear();
                            PcsEdit = null;
                            foreach (var item in pcses)
                            {
                                PcsList1.Add(new PcsDisp
                                {
                                    Id = item.Index,
                                    IsUse = item.IsUse,
                                    ProductId = product1.PcsOrder,
                                    X = Math.Round(item.X, 3),
                                    Y = Math.Round(item.Y, 3),
                                    Z = Math.Round(item.Z, 3),
                                    R = Math.Round(item.R, 2),
                                    X1 = Math.Round(item.X1, 3),
                                    Y1 = Math.Round(item.Y1, 3),
                                    Z1 = Math.Round(item.Z1, 3),
                                    R1 = Math.Round(item.R1, 2),
                                    PickIndex = item.PickIndex,
                                    PressIndex = item.PressIndex
                                });
                            }
                        }
                    }
                }
            }
        }
        void ExecuteSelectFloorCommand(object obj)
        {
            FloorIndex = int.Parse(obj.ToString());
            //Debug.WriteLine(FloorIndex);
            IsAssistantPointEditVisible = FloorIndex != 1;
            LoadProductList(FloorIndex);
        }
        void ExecuteOpenFileCommand()
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "Dxf文件(*.dxf)|*.dxf|所有文件|*.*";
            if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                LwPolylineList.Clear();
                bool isBinary;
                // this check is optional but recommended before loading a DXF file
                DxfVersion dxfVersion = DxfDocument.CheckDxfFileVersion(ofd.FileName, out isBinary);
                // netDxf is only compatible with AutoCad2000 and higher DXF version
                if (dxfVersion < DxfVersion.AutoCad2000) return;
                // load file
                DxfDocument dxf = DxfDocument.Load(ofd.FileName);
                Circle circleorg = dxf.Circles.FirstOrDefault(cirle => cirle.Layer.Name == "myorg");
                if (circleorg != null)
                {
                    var circleOrgx = circleorg.Center.X;
                    var circleOrgy = circleorg.Center.Y;
                    
                    LwPolyline? lwPolylinesBorder = dxf.LwPolylines.FirstOrDefault(p => p.Layer.Name == "myborder");
                    if (lwPolylinesBorder != null)
                    {

                        var minx = lwPolylinesBorder.Vertexes.Min(p => p.Position.X);//载具图纸原点X
                        var miny = lwPolylinesBorder.Vertexes.Min(p => p.Position.Y);//载具图纸原点Y
                        var maxx = lwPolylinesBorder.Vertexes.Max(p => p.Position.X);//反面原点X
                        var maxy = lwPolylinesBorder.Vertexes.Max(p => p.Position.Y);
                        double width = maxx - minx;
                        double height = maxy - miny;
                        OrgWidth = width;
                        OrgHeight = height;
                        OrgPX = circleOrgx - minx;
                        OrgPY = circleOrgy - miny;
                        OrgNX = maxx - circleOrgx;
                        OrgNY = circleOrgy - miny;
                        using (var db = new DTContext(partNum))
                        {
                            foreach (var item in db.MProducts)
                            {
                                db.MProducts.Remove(item);
                            }
                            var param = db.MParams.FirstOrDefault(p => p.Name == "OrgWidth");
                            if (param != null)
                            {
                                param.Value = width.ToString("F3");
                            }
                            param = db.MParams.FirstOrDefault(p => p.Name == "OrgHeight");
                            if (param != null)
                            {
                                param.Value = height.ToString("F3");
                            }
                            param = db.MParams.FirstOrDefault(p => p.Name == "OrgX" && p.Floor == 1);
                            if (param != null)
                            {
                                param.Value = OrgPX.ToString("F3");
                            }
                            param = db.MParams.FirstOrDefault(p => p.Name == "OrgY" && p.Floor == 1);
                            if (param != null)
                            {
                                param.Value = OrgPY.ToString("F3");
                            }
                            param = db.MParams.FirstOrDefault(p => p.Name == "OrgX" && p.Floor == 2);
                            if (param != null)
                            {
                                param.Value = OrgNX.ToString("F3");
                            }
                            param = db.MParams.FirstOrDefault(p => p.Name == "OrgY" && p.Floor == 2);
                            if (param != null)
                            {
                                param.Value = OrgNY.ToString("F3");
                            }

                            db.SaveChanges();
                        }
                        LwPolylineList.Add(new LwPolylineDisp
                        {
                            Id = 0,
                            Kind = 0,
                            Floor = 1,
                            Left = 10,
                            Bottom = 10,
                            Width = width / 2,
                            Height = height / 2,
                            BorderColor = "#0000FF",
                            BorderThickness = 1
                        });
                        //正面产品
                        //var grabPoint = PointList1.FirstOrDefault(p => p.Name == "TopCameraBoardOrgGrab" && p.Floor == 1);
                        var orgPoint = PointList1.FirstOrDefault(p => p.Name == "OrgBoard" && p.Floor == 1);
                        List<LwPolyline> lwPolylinesProductP = dxf.LwPolylines.Where(p => p.Layer.Name == "myproductp").ToList();
                        if (lwPolylinesProductP.Any())
                        {
                            int pcsorder = 0;
                            using (var db = new DTContext(partNum))
                            {
                                foreach (var item in lwPolylinesProductP)
                                {
                                    var minx1 = item.Vertexes.Min(p => p.Position.X);
                                    var miny1 = item.Vertexes.Min(p => p.Position.Y);
                                    var maxx1 = item.Vertexes.Max(p => p.Position.X);
                                    var maxy1 = item.Vertexes.Max(p => p.Position.Y);
                                    double width1 = maxx1 - minx1;
                                    double height1 = maxy1 - miny1;
                                    LwPolylineList.Add(new LwPolylineDisp
                                    {
                                        Id = pcsorder,
                                        ProductId = pcsorder,
                                        Kind = 1,
                                        Floor = 1,
                                        Left = 10 + (minx1 - minx) / 2,
                                        Bottom = 10 + (miny1 - miny) / 2,
                                        Width = width1 / 2,
                                        Height = height1 / 2,
                                        BorderColor = "#FF7F00",
                                        BorderThickness = 1
                                    });
                                    MProduct mProduct = new MProduct()
                                    {
                                        Pcses = new List<MPcs>(),
                                        PcsOrder = pcsorder,
                                        IsUse = true,
                                        IsReverse = false,
                                        Order = width1 > height1 ? 0 : 1,//宽度大于高度，就选X方向
                                        Direction = 0,//默认增方向
                                        StartX = minx1 - minx + (orgPoint.X - OrgPX),
                                        StartY = miny1 - miny + (orgPoint.Y - OrgPY),
                                        EndX = maxx1 - minx + (orgPoint.X - OrgPX),
                                        EndY = maxy1 - miny + (orgPoint.Y - OrgPY),
                                        Floor = 1,//正面
                                    };
                                    List<LwPolyline> lwPolylinesPcsP = dxf.LwPolylines.Where(p => p.Layer.Name == "mypcsp"
                                        && (p.Vertexes.Min(q => q.Position.X) + p.Vertexes.Max(q => q.Position.X)) / 2 > minx1
                                        && (p.Vertexes.Min(q => q.Position.X) + p.Vertexes.Max(q => q.Position.X)) / 2 < maxx1
                                        && (p.Vertexes.Min(q => q.Position.Y) + p.Vertexes.Max(q => q.Position.Y)) / 2 > miny1
                                        && (p.Vertexes.Min(q => q.Position.Y) + p.Vertexes.Max(q => q.Position.Y)) / 2 < maxy1).ToList();
                                    if (lwPolylinesPcsP.Any())//依据坐标排个序
                                    {
                                        if (width1 > height1)
                                        {
                                            lwPolylinesPcsP.Sort((x, y) => ((x.Vertexes.Min(q => q.Position.X) + x.Vertexes.Max(q => q.Position.X)) / 2).CompareTo((y.Vertexes.Min(q => q.Position.X) + y.Vertexes.Max(q => q.Position.X)) / 2));
                                        }
                                        else
                                        {
                                            lwPolylinesPcsP.Sort((x, y) => ((x.Vertexes.Min(q => q.Position.Y) + x.Vertexes.Max(q => q.Position.Y)) / 2).CompareTo((y.Vertexes.Min(q => q.Position.Y) + y.Vertexes.Max(q => q.Position.Y)) / 2));
                                        }
                                    }
                                    int pcsindex = 0;
                                    foreach (var pcs in lwPolylinesPcsP)
                                    {
                                        var minx2 = pcs.Vertexes.Min(p => p.Position.X);
                                        var miny2 = pcs.Vertexes.Min(p => p.Position.Y);
                                        var maxx2 = pcs.Vertexes.Max(p => p.Position.X);
                                        var maxy2 = pcs.Vertexes.Max(p => p.Position.Y);
                                        double width2 = maxx2 - minx2;
                                        double height2 = maxy2 - miny2;
                                        MPcs mpcs = new MPcs()
                                        {
                                            Index = pcsindex,
                                            IsUse = true,
                                            X = (pcs.Vertexes.Min(q => q.Position.X) + pcs.Vertexes.Max(q => q.Position.X)) / 2 - minx + (orgPoint.X - OrgPX),
                                            Y = (pcs.Vertexes.Min(q => q.Position.Y) + pcs.Vertexes.Max(q => q.Position.Y)) / 2 - miny + (orgPoint.Y - OrgPY),
                                            R = 0,
                                            Z = 0,
                                            Width = width2,
                                            Height = height2,
                                            X1 = 0,
                                            Y1 = 0,
                                            R1 = 0,
                                            Z1 = 0
                                        };
                                        mProduct.Pcses.Add(mpcs);
                                        LwPolylineList.Add(new LwPolylineDisp
                                        {
                                            Id = pcsindex,
                                            ProductId = pcsorder,
                                            Kind = 2,
                                            Floor = 1,
                                            Left = 10 + (minx2 - minx) / 2,
                                            Bottom = 10 + (miny2 - miny) / 2,
                                            Width = width2 / 2,
                                            Height = height2 / 2,
                                            BorderColor = "#7B68EE",
                                            BorderThickness = 1
                                        });
                                        pcsindex++;
                                    }
                                    pcsorder++;
                                    db.MProducts.Add(mProduct);
                                }
                                db.SaveChanges();
                            }
                        }
                        //反面产品
                        //grabPoint = PointList1.FirstOrDefault(p => p.Name == "TopCameraBoardOrgGrab" && p.Floor == 2);
                        var orgPointP = PointList1.FirstOrDefault(p => p.Name == "OrgBoard" && p.Floor == 1);
                        orgPoint = PointList1.FirstOrDefault(p => p.Name == "OrgBoard" && p.Floor == 2);
                        List<LwPolyline> lwPolylinesProductN = dxf.LwPolylines.Where(p => p.Layer.Name == "myproductn").ToList();
                        if (lwPolylinesProductN.Any())
                        {
                            int pcsorder = 0;
                            using (var db = new DTContext(partNum))
                            {
                                foreach (var item in lwPolylinesProductN)
                                {
                                    var minx1 = item.Vertexes.Min(p => p.Position.X);
                                    var miny1 = item.Vertexes.Min(p => p.Position.Y);
                                    var maxx1 = item.Vertexes.Max(p => p.Position.X);
                                    var maxy1 = item.Vertexes.Max(p => p.Position.Y);
                                    double width1 = maxx1 - minx1;
                                    double height1 = maxy1 - miny1;
                                    LwPolylineList.Add(new LwPolylineDisp
                                    {
                                        Id = pcsorder,
                                        ProductId = pcsorder,
                                        Kind = 1,
                                        Floor = 2,
                                        Left = 10 + (minx1 - minx) / 2,
                                        Bottom = 10 + (miny1 - miny) / 2,
                                        Width = width1 / 2,
                                        Height = height1 / 2,
                                        BorderColor = "#BF00FF",
                                        BorderThickness = 1
                                    });
                                    MProduct mProduct = new MProduct()
                                    {
                                        Pcses = new List<MPcs>(),
                                        PcsOrder = pcsorder,
                                        IsUse = true,
                                        IsReverse = false,
                                        Order = width1 > height1 ? 0 : 1,//宽度大于高度，就选X方向
                                        Direction = 0,//默认增方向
                                        StartX = (maxx1 - maxx) * -1 + (orgPoint.X - OrgNX),
                                        StartY = miny1 - miny + (orgPoint.Y - OrgNY),
                                        EndX = (minx1 - maxx) * -1 + (orgPoint.X - OrgNX),
                                        EndY = maxy1 - miny + (orgPoint.Y - OrgNY),
                                        Floor = 2//反面
                                    };
                                    List<LwPolyline> lwPolylinesPcsN = dxf.LwPolylines.Where(p => p.Layer.Name == "mypcsn"
                                        && (p.Vertexes.Min(q => q.Position.X) + p.Vertexes.Max(q => q.Position.X)) / 2 > minx1
                                        && (p.Vertexes.Min(q => q.Position.X) + p.Vertexes.Max(q => q.Position.X)) / 2 < maxx1
                                        && (p.Vertexes.Min(q => q.Position.Y) + p.Vertexes.Max(q => q.Position.Y)) / 2 > miny1
                                        && (p.Vertexes.Min(q => q.Position.Y) + p.Vertexes.Max(q => q.Position.Y)) / 2 < maxy1).ToList();
                                    if (lwPolylinesPcsN.Any())
                                    {
                                        if (width1 > height1)
                                        {
                                            lwPolylinesPcsN.Sort((x, y) => ((y.Vertexes.Min(q => q.Position.X) + y.Vertexes.Max(q => q.Position.X)) / 2).CompareTo((x.Vertexes.Min(q => q.Position.X) + x.Vertexes.Max(q => q.Position.X)) / 2));
                                        }
                                        else
                                        {
                                            lwPolylinesPcsN.Sort((x, y) => ((x.Vertexes.Min(q => q.Position.Y) + x.Vertexes.Max(q => q.Position.Y)) / 2).CompareTo((y.Vertexes.Min(q => q.Position.Y) + y.Vertexes.Max(q => q.Position.Y)) / 2));
                                        }
                                    }
                                    int pcsindex = 0;
                                    foreach (var pcs in lwPolylinesPcsN)
                                    {
                                        var minx2 = pcs.Vertexes.Min(p => p.Position.X);
                                        var miny2 = pcs.Vertexes.Min(p => p.Position.Y);
                                        var maxx2 = pcs.Vertexes.Max(p => p.Position.X);
                                        var maxy2 = pcs.Vertexes.Max(p => p.Position.Y);
                                        double width2 = maxx2 - minx2;
                                        double height2 = maxy2 - miny2;
                                        MPcs mpcs = new MPcs()
                                        {
                                            Index = pcsindex,
                                            IsUse = true,
                                            X = ((pcs.Vertexes.Min(q => q.Position.X) + pcs.Vertexes.Max(q => q.Position.X)) / 2 - maxx) * -1 + (orgPoint.X - OrgNX),
                                            Y = (pcs.Vertexes.Min(q => q.Position.Y) + pcs.Vertexes.Max(q => q.Position.Y)) / 2 - miny + (orgPoint.Y - OrgNY),
                                            R = 0,
                                            Z = 0,
                                            Width = width2,
                                            Height = height2,
                                            X1 = (pcs.Vertexes.Min(q => q.Position.X) + pcs.Vertexes.Max(q => q.Position.X)) / 2 - minx + (orgPointP.X - OrgPX),
                                            Y1 = (pcs.Vertexes.Min(q => q.Position.Y) + pcs.Vertexes.Max(q => q.Position.Y)) / 2 - miny + (orgPointP.Y - OrgPY),
                                            R1 = 0,
                                            Z1 = 0
                                        };
                                        mProduct.Pcses.Add(mpcs);
                                        LwPolylineList.Add(new LwPolylineDisp
                                        {
                                            Id = pcsindex,
                                            ProductId = pcsorder,
                                            Kind = 2,
                                            Floor = 2,
                                            Left = 10 + (minx2 - minx) / 2,
                                            Bottom = 10 + (miny2 - miny) / 2,
                                            Width = width2 / 2,
                                            Height = height2 / 2,
                                            BorderColor = "#FF007F",
                                            BorderThickness = 1
                                        });
                                        pcsindex++;
                                    }
                                    pcsorder++;
                                    db.MProducts.Add(mProduct);
                                }
                                db.SaveChanges();
                            }
                        }
                    }
                }


                LoadProductList(FloorIndex);
                _dialogHostService.MessageBox(MessageType.Message, "信息", "DXF读取完成");
            }
        }
        #endregion
        #region 导航
        public override void OnDialogOpened(IDialogParameters parameters)
        {
            partNum = parameters.GetValue<string>("PartNum");
            using (var db = new DTContext(partNum))
            {
                var points = db.XYZRPoints.Where(p => (p.Name == "TopCameraBoardOrgGrab" || p.Name == "OrgBoard") && p.Floor == 1);
                if (points.Any())
                {
                    var posList = points.ToList();
                    foreach (var item in posList)
                    {
                        PointList1.Add(
                            new AxisPointDisp
                            {
                                Id = item.Id,
                                Name = item.Name,
                                Alias = item.Alias + "(正面)",
                                X = item.X,
                                Y = item.Y,
                                Z = item.Z,
                                R = item.R,
                                ZIndex = item.ZIndex,
                                RIndex = item.RIndex,
                                Floor = item.Floor
                            }
                            );
                    }
                }
                points = db.XYZRPoints.Where(p => (p.Name == "TopCameraBoardOrgGrab" || p.Name == "OrgBoard") && p.Floor == 2);
                if (points.Any())
                {
                    var posList = points.ToList();
                    foreach (var item in posList)
                    {
                        PointList1.Add(
                            new AxisPointDisp
                            {
                                Id = item.Id,
                                Name = item.Name,
                                Alias = item.Alias + "(反面)",
                                X = item.X,
                                Y = item.Y,
                                Z = item.Z,
                                R = item.R,
                                ZIndex = item.ZIndex,
                                RIndex = item.RIndex,
                                Floor = item.Floor
                            }
                            );
                    }
                }

                var v1 = db.MParams.FirstOrDefault(p => p.Name == "OrgWidth");
                
                if (v1 != null)
                {
                    OrgWidth = double.Parse(v1.Value);
                }
                v1 = db.MParams.FirstOrDefault(p => p.Name == "OrgHeight");
                
                if (v1 != null)
                {
                    OrgHeight = double.Parse(v1.Value);
                }
                v1 = db.MParams.FirstOrDefault(p => p.Name == "OrgX" && p.Floor == 1);

                if (v1 != null)
                {
                    OrgPX = double.Parse(v1.Value);
                }
                v1 = db.MParams.FirstOrDefault(p => p.Name == "OrgY" && p.Floor == 1);

                if (v1 != null)
                {
                    OrgPY = double.Parse(v1.Value);
                }
                v1 = db.MParams.FirstOrDefault(p => p.Name == "OrgX" && p.Floor == 2);

                if (v1 != null)
                {
                    OrgNX = double.Parse(v1.Value);
                }
                v1 = db.MParams.FirstOrDefault(p => p.Name == "OrgY" && p.Floor == 2);

                if (v1 != null)
                {
                    OrgNY = double.Parse(v1.Value);
                }
                LwPolylineList.Add(new LwPolylineDisp
                {
                    Id = 0,
                    Kind = 0,
                    Floor = 1,
                    Left = 10,
                    Bottom = 10,
                    Width = OrgWidth / 2,
                    Height = OrgHeight / 2,
                    BorderColor = "#0000FF",
                    BorderThickness = 1
                });

                //var grabPoint = PointList1.FirstOrDefault(p => p.Name == "TopCameraBoardOrgGrab" && p.Floor == 1);
                var orgPoint = PointList1.FirstOrDefault(p => p.Name == "OrgBoard" && p.Floor == 1);
                FloorIndex = 1;
                var products = db.MProducts.Where(p => p.Floor == 1).ToList();
                if (products.Any())
                {
                    foreach (var item in products)
                    {
                        LwPolylineList.Add(new LwPolylineDisp
                        {
                            Id = item.PcsOrder,
                            ProductId = item.PcsOrder,
                            Kind = 1,
                            Floor = 1,
                            Left = 10 + (item.StartX - (orgPoint.X - OrgPX)) / 2,
                            Bottom = 10 + (item.StartY - (orgPoint.Y - OrgPY)) / 2,
                            Width = (item.EndX - item.StartX) / 2,
                            Height = (item.EndY - item.StartY) / 2,
                            BorderColor = "#FF7F00",
                            BorderThickness = 1
                        });
                     
                        if (item.Pcses.Any())
                        {
                            foreach (var pcs in item.Pcses.ToList())
                            {
                                LwPolylineList.Add(new LwPolylineDisp
                                {
                                    Id = pcs.Index,
                                    ProductId = item.PcsOrder,
                                    Kind = 2,
                                    Floor = 1,
                                    Left = 10 + (pcs.X - pcs.Width / 2 - (orgPoint.X - OrgPX)) / 2,
                                    Bottom = 10 + (pcs.Y - pcs.Height / 2 - (orgPoint.Y - OrgPY)) / 2,
                                    Width = pcs.Width / 2,
                                    Height = pcs.Height / 2,
                                    BorderColor = "#7B68EE",
                                    BorderThickness = 1
                                });
                            }
                        }
                    }
                }

                //grabPoint = PointList1.FirstOrDefault(p => p.Name == "TopCameraBoardOrgGrab" && p.Floor == 2);
                orgPoint = PointList1.FirstOrDefault(p => p.Name == "OrgBoard" && p.Floor == 2);
                products = db.MProducts.Where(p => p.Floor == 2).ToList();
                if (products.Any())
                {
                    foreach (var item in products)
                    {
                        LwPolylineList.Add(new LwPolylineDisp
                        {
                            Id = item.PcsOrder,
                            ProductId = item.PcsOrder,
                            Kind = 1,
                            Floor = 2,
                            Left = 10 + (OrgWidth - (item.StartX - (orgPoint.X - OrgNX)) - (item.EndX - item.StartX)) / 2,
                            Bottom = 10 + (item.StartY - (orgPoint.Y - OrgNY)) / 2,
                            Width = (item.EndX - item.StartX) / 2,
                            Height = (item.EndY - item.StartY) / 2,
                            BorderColor = "#BF00FF",
                            BorderThickness = 1
                        });
                        if (item.Pcses.Any())
                        {
                            foreach (var pcs in item.Pcses.ToList())
                            {
                                LwPolylineList.Add(new LwPolylineDisp
                                {
                                    Id = pcs.Index,
                                    ProductId = item.PcsOrder,
                                    Kind = 2,
                                    Floor = 2,
                                    Left = 10 + (OrgWidth - ((pcs.X - (orgPoint.X - OrgNX)) + pcs.Width / 2) ) / 2,
                                    Bottom = 10 + (pcs.Y - pcs.Height / 2 - (orgPoint.Y - OrgNY)) / 2,
                                    Width = pcs.Width / 2,
                                    Height = pcs.Height / 2,
                                    BorderColor = "#FF007F",
                                    BorderThickness = 1
                                });
                            }
                        }
                    }
                }
            }
            LoadProductList(FloorIndex);
            //FloorIndex = 1;
        }
        #endregion
        public PastePointDialogViewModel(IContainerProvider containerProvider) : base(containerProvider)
        {
            Title = "贴合点";
            LwPolylineList = new ObservableCollection<LwPolylineDisp>();
            ProductList1 = new ObservableCollection<ProductDisp>();
            PcsList1 = new ObservableCollection<PcsDisp>();
            PointList1 = new ObservableCollection<AxisPointDisp>();
            IsAssistantPointEditVisible = false;
            SuckerEditDeltaIndex = 0;
            PcsDeltaEdit = new PcsEditDeltaDisp();
        }
        #region 功能函数
        private void LoadProductList(int floor)
        {
            ProductList1.Clear();
            ProductEdit = null;
            PcsEdit = null;
            PcsList1.Clear();
            using (var db = new DTContext(partNum))
            {
                var products = db.MProducts.Where(p => p.Floor == floor).OrderBy(p => p.PcsOrder).ToList();
                if (products.Any())
                {
                    foreach (var item in products)
                    {
                        ProductList1.Add(new ProductDisp
                        {
                            Id = item.PcsOrder,
                            IsUse = item.IsUse,
                            IsReverse = item.IsReverse ? "是":"否",
                            Order = item.Order == 0 ? "X" : "Y",
                            Direction = item.Direction == 0 ? "增" : "减",
                            StartX = Math.Round(item.StartX, 3),
                            StartY = Math.Round(item.StartY, 3),
                            EndX = Math.Round(item.EndX, 3),
                            EndY = Math.Round(item.EndY, 3)
                        });
                    }
                }
            }
        }
        private void ReLoadProductLwPolylineList(int floor)
        {
            var lines = LwPolylineList.Where(l => (l.Kind == 1 || l.Kind == 2) && l.Floor == floor).ToList();
            if (lines.Any())
            {
                foreach (var item in lines)
                {
                    LwPolylineList.Remove(item);
                }
            }
            using (var db = new DTContext(partNum))
            {
                var products = db.MProducts.Where(p => p.Floor == floor).ToList();
                if (products.Any())
                {
                    var orgPoint = PointList1.FirstOrDefault(p => p.Name == "OrgBoard" && p.Floor == 2);
                    foreach (var item in products)
                    {
                        switch (floor)
                        {
                            case 1:
                                LwPolylineList.Add(new LwPolylineDisp
                                {
                                    Id = item.PcsOrder,
                                    Kind = 1,
                                    Floor = floor,
                                    Left = 10 + (item.StartX - (orgPoint.X - OrgPX)) / 2,
                                    Bottom = 10 + (item.StartY - (orgPoint.Y - OrgPY)) / 2,
                                    Width = (item.EndX - item.StartX) / 2,
                                    Height = (item.EndY - item.StartY) / 2,
                                    BorderColor = "#FF7F00",
                                    BorderThickness = 1
                                });
                                if (item.Pcses.Any())
                                {
                                    foreach (var pcs in item.Pcses.ToList())
                                    {
                                        LwPolylineList.Add(new LwPolylineDisp
                                        {
                                            Id = pcs.Index,
                                            ProductId = item.PcsOrder,
                                            Kind = 2,
                                            Floor = 1,
                                            Left = 10 + (pcs.X - pcs.Width / 2 - (orgPoint.X - OrgPX)) / 2,
                                            Bottom = 10 + (pcs.Y - pcs.Height / 2 - (orgPoint.Y - OrgPY)) / 2,
                                            Width = pcs.Width / 2,
                                            Height = pcs.Height / 2,
                                            BorderColor = "#7B68EE",
                                            BorderThickness = 1
                                        });
                                    }
                                }
                                break;
                            case 2:
                                LwPolylineList.Add(new LwPolylineDisp
                                {
                                    Id = item.PcsOrder,
                                    Kind = 1,
                                    Floor = floor,
                                    Left = 10 + (OrgWidth - (item.StartX - (orgPoint.X - OrgNX)) - (item.EndX - item.StartX)) / 2,
                                    Bottom = 10 + (item.StartY - (orgPoint.Y - OrgNY)) / 2,
                                    Width = (item.EndX - item.StartX) / 2,
                                    Height = (item.EndY - item.StartY) / 2,
                                    BorderColor = "#FF7F00",
                                    BorderThickness = 1
                                });
                                if (item.Pcses.Any())
                                {
                                    foreach (var pcs in item.Pcses.ToList())
                                    {
                                        LwPolylineList.Add(new LwPolylineDisp
                                        {
                                            Id = pcs.Index,
                                            ProductId = item.PcsOrder,
                                            Kind = 2,
                                            Floor = 2,
                                            Left = 10 + (OrgWidth - ((pcs.X - (orgPoint.X - OrgNX)) + pcs.Width / 2)) / 2,
                                            Bottom = 10 + (pcs.Y - pcs.Height / 2 - (orgPoint.Y - OrgNY)) / 2,
                                            Width = pcs.Width / 2,
                                            Height = pcs.Height / 2,
                                            BorderColor = "#FF007F",
                                            BorderThickness = 1
                                        });
                                    }
                                }
                                break;
                            default:
                                break;
                        }
                
                    }
                }
            }
        }
        #endregion
    }
}
